const Router = require('koa-router');
const query = require('../util/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');
const R = require('ramda/src');

const router = new Router();

router.prefix('/api/carousel');

module.exports = router;

/**
 * 获取所有轮播
 */
router.get('/all', async (ctx, next) => {
  const res = await query('select * from carousel');
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  const arr = R.sort((a, b) => a.rank - b.rank)(res);
  ctx.body = await wrapper(arr);
});

/**
 * 修改轮播
 */
router.post('/edit', async (ctx, next) => {
  const { carousel } = ctx.request.body;
  if (!Array.isArray(carousel) || carousel.length === 0) {
    ctx.body = await wrapper(new Error('缺少参数.'));
    return false;
  }
  for (let i = 0, len = carousel.length; i < len; i++) {
    const { id, url, rank } = carousel[i];
    if (!id || !url) {
      ctx.body = await wrapper(new Error('参数为空'));
      return false;
    }
    const checkRes = await query(`select * from carousel where id=${id}`);
    if (checkError(checkRes)) {
      ctx.body = await wrapper(new Error('服务异常.'));
      return false;
    }
    const { url: c_url, rank: c_rank } = checkRes;
    if (checkRes.length === 0) {
      await query(`insert into carousel(url,rank) values('${url}','${rank}')`).catch(err => console.log(err));
    } else if (c_url !== url || c_rank !== rank) {
      await query(`update carousel set url='${url}',rank='${rank}' where id=${id}`).catch(err => console.log(err));
    }
  }
  ctx.body = await wrapper('更新成功');
});

/**
 * 删除轮播
 */
router.post('/del', async (ctx, next) => {
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = await wrapper(new Error('缺少参数.'));
    return false;
  }

  const delRes = await query(`delete from carousel where id=${id}`);
  if (checkError(delRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper('删除成功');
});
